# Maintainer: Ben Orchard <thefirstmuffinman@gmail.com>

_realname=flint
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=3.2.2
pkgrel=1
pkgdesc="Fast Library for Number Theory (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://www.flintlib.org/"
msys2_repository_url="https://github.com/flintlib/flint"
msys2_references=(
  'archlinux: flint'
)
license=('spdx:LGPL-3.0-or-later')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-mpfr"
         "${MINGW_PACKAGE_PREFIX}-gmp"
         "${MINGW_PACKAGE_PREFIX}-openblas"
         "${MINGW_PACKAGE_PREFIX}-libwinpthread-git")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-python")
source=(https://github.com/flintlib/flint/releases/download/v${pkgver}/${_realname}-${pkgver}.tar.xz)
sha256sums=('518248b9cd523fab8d84a010b892047dfc97908489ae15199472648165d2a118')

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd ${_realname}-${pkgver}
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${MINGW_PACKAGE_PREFIX} != *-clang-* ]]; then
    _extra_config+=("-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=OFF")
  fi

  if [[ ${CARCH} == x86_64 ]]; then
    _extra_config+=("-DENABLE_AVX2=ON")
  else
    _extra_config+=("-DENABLE_AVX2=OFF")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G Ninja \
    -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
    -DENABLE_ARCH=NO \
    "${_extra_config[@]}" \
    -DPython_EXECUTABLE=${MINGW_PREFIX}/bin/python \
    -DBUILD_TESTING=OFF \
    "../${_realname}-${pkgver}"

  ${MINGW_PREFIX}/bin/cmake.exe --build .
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  ${MINGW_PREFIX}/bin/cmake ../${_realname}-${pkgver} -DBUILD_TESTING=ON
  ${MINGW_PREFIX}/bin/cmake --build .
  ${MINGW_PREFIX}/bin/ctest.exe . --output-on-failure || echo "Tests failed"
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .
  install -Dm0644 -t "${pkgdir}"${MINGW_PREFIX}/share/licenses/${_realname}/ \
    "${srcdir}"/${_realname}-${pkgver}/COPYING*
}
